package com.csc.service.impl;

import com.csc.entity.Allocation;
import com.csc.entity.Dormitory;
import com.csc.entity.Student;
import com.csc.mapper.AllocationMapper;
import com.csc.mapper.DormitoryMapper;
import com.csc.mapper.StudentMapper;
import com.csc.service.AllocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AllocationServiceImpl implements AllocationService {

    @Autowired
    private AllocationMapper allocationMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public void allocate(Long studentId, Long dormitoryId) {
        Student student = studentMapper.findById(studentId);
        if(student == null) {
            throw new RuntimeException("学生不存在");
        }

        Dormitory dormitory = dormitoryMapper.findById(dormitoryId);
        if(dormitory == null) {
            throw new RuntimeException("宿舍不存在");
        }
        if(dormitory.getAvailableBeds()  <= 0) {
            throw new RuntimeException("该宿舍已满");
        }

        allocationMapper.cancelAllocation(studentId);

        Allocation allocation = new Allocation();
        allocation.setStudentId(studentId);
        allocation.setDormitoryId(dormitoryId);
        allocation.setAllocateDate(new  Date());
        allocationMapper.allocate(allocation);

        allocationMapper.updateAvailableBeds(dormitoryId,  -1);
    }

    @Override
    public void cancel(Long studentId) {
        List<Allocation> allocations = allocationMapper.findByStudentId(studentId);
        if(allocations.isEmpty())  {
            throw new RuntimeException("该学生未分配宿舍");
        }

        allocationMapper.cancelAllocation(studentId);

        for(Allocation allocation : allocations) {
            allocationMapper.updateAvailableBeds(allocation.getDormitoryId(),  1);
        }
    }

    @Override
    public List<Allocation> getStudentAllocations(Long studentId) {
        return allocationMapper.findByStudentId(studentId);
    }

    @Override
    public List<Allocation> getDormitoryAllocations(Long dormitoryId) {
        return allocationMapper.findByDormitoryId(dormitoryId);
    }
}